package com.glut.campusrepair.controller;

import com.glut.campusrepair.dto.MaintenanceLongRecordsdto;
import com.glut.campusrepair.dto.RepairTasksShortdto;
import com.glut.campusrepair.entity.RepairTasks;
import com.glut.campusrepair.mapper.ServiceEvaluationMapper;
import com.glut.campusrepair.service.IRepairTasksService;
import com.glut.campusrepair.service.IServiceEvaluationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;


/**
 * 维修进度表 前端控制器
 *
 * @author sanminzhi
 * @since 2024-07-19 11:26
 */
@RestController
@RequestMapping("/repair-tasks")
@CrossOrigin
public class RepairTasksController {

    @Autowired
    IRepairTasksService iRepairTasksService;

    RepairTasksShortdto repairTasksShortdto;

    /**
     * 通过维修人员id查询所有简洁版的待接受的任务，再通过其中的故障报修id查找出相应的报修的故障信息
     * */
    @GetMapping("/getPendingTasksByRepairPersonnelId/{repairPersonnelId}")
    public List<RepairTasksShortdto> getPendingTasksByRepairPersonnelId(@PathVariable Integer repairPersonnelId) {
        List<RepairTasksShortdto> pendingTasksByRepairPersonnelId = iRepairTasksService.selectAssociation(repairPersonnelId);
        return pendingTasksByRepairPersonnelId;
    }


    /**
     * 根据维修人员Id查询所有任务（传入维修人员id参数，任务状态参数）
     * 点击你的任务时，传入的任务状态参数（status）值为'正在处理'
     * 点击新任务时，传入的任务状态参数（status）值为'待接受'
     * */
    @GetMapping("/getAllTasksByRepairPersonnelId")
    public List<RepairTasksShortdto> getAllTasksByRepairPersonnelId(@RequestParam Integer repairPersonnelId,
                                                                    @RequestParam String status
    ){
        repairTasksShortdto = new RepairTasksShortdto();
        repairTasksShortdto.setRepairPersonnelId(repairPersonnelId);
        repairTasksShortdto.setStatus(status);

        List<RepairTasksShortdto> allTasksByRepairPersonnelId = iRepairTasksService.selectTasksById(repairTasksShortdto);
        return allTasksByRepairPersonnelId;
    }

    /**
     * 接受任务
     * 点击接受任务时，将repair_task表中的任务状态参数（status）值为'正在处理',并将接受任务的时间赋值给acceptance_time属性
     * */
    @PutMapping("/acceptTask")
    public boolean acceptTask(@RequestParam Integer taskId){
        return  iRepairTasksService.updateById(taskId);
    }


    @GetMapping("/set/{id}")
    public RepairTasks setRepairTasks(@PathVariable Integer id){
        return iRepairTasksService.setRepairTasks(id);
    }

    @PostMapping("/upload/{employeeId}")
    public ResponseEntity<ResponseResult> uploadFiles(@RequestParam("files") MultipartFile[] files, @PathVariable Integer employeeId ) {

        // 判断是否有文件
        if (files == null || files.length == 0) {
            return ResponseEntity.badRequest().body(ResponseResult.fail());
        }

        String completionPhoto = "";

        // 设置保存路径
        String path = "D:/学习文件/蓝桥/高级项目/备份/2/源/Campus-Repair-fronted/src/assets/"; // 路径使用正斜杠
        File directory = new File(path);

        // 确保目录存在
        if (!directory.exists()) {
            directory.mkdirs();
        }

        for (MultipartFile file : files) {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();

            // 防止重名覆盖，使用系统时间戳加原始文件后缀
            String fileName = System.currentTimeMillis() + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            try {
                // 创建文件
                File dest = new File(directory, fileName);

                // 保存文件
                file.transferTo(dest);
                //保存文件路径
                completionPhoto = path + fileName;
                iRepairTasksService.upCompletionPhoto(employeeId,completionPhoto);
                // 返回成功响应
                return ResponseEntity.ok(new ResponseResult(200, "文件上传成功", fileName));
            } catch (IOException e) {
                e.printStackTrace();
                // 返回失败响应
                return ResponseEntity.status(500).body(ResponseResult.fail());
            }
        }

        // 如果所有文件都上传成功
        return ResponseEntity.ok(new ResponseResult(200, "所有文件上传成功", null));
    }


    @GetMapping("/getPhoto/{taskId}")
    public String getCompletionPhoto(@PathVariable Integer taskId){
        return iRepairTasksService.getCompletionPhoto(taskId);
    }
}
